package com.opNaga.bpmn.actions.io;

import com.opNaga.bpmn.panel.BPMPPanel;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * User: Junyi BEI
 * Date: 20/03/2012
 * Time: 16:07
 */
public class Open extends AbstractAction {
  private static final String RESOURCE_PATH = "./resource/ide/image";
  JTabbedPane tabbedPane;
  JFileChooser chooser;

  public Open(JTabbedPane tabbedPane) {
    this.tabbedPane = tabbedPane;
  }

  public void actionPerformed(ActionEvent e) {
    if(chooser == null) {
      chooser = new JFileChooser();
      chooser.setAcceptAllFileFilterUsed(false);
      chooser.addChoosableFileFilter(new FileFilter() {
        public boolean accept(File f) {
          return f.isDirectory() || f.getName().endsWith(".bpmp");
        }

        public String getDescription() {
          return "BPMP Format (.bpmp)";
        }
      });
    }
    if(chooser.showOpenDialog(tabbedPane) == JFileChooser.APPROVE_OPTION) {
      try {
        ZipFile zipFile = new ZipFile(chooser.getSelectedFile());
        Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
        while(zipEntries.hasMoreElements()) {
          ZipEntry zipEntry = zipEntries.nextElement();
          String fileName = zipEntry.getName();
          String tabString = "";
          int fileNameLength = fileName.length();
          for(int i = 0; i < fileNameLength; i++) {
            char c = fileName.charAt(i);
            if(!tabString.isEmpty() && !Character.isDigit(c)) {
              break;
            }
            if(Character.isDigit(c)) {
              tabString += c;
            }
          }
          int tab = Integer.valueOf(tabString);
          InputStream inputStream = zipFile.getInputStream(zipEntry);
          BPMPPanel bpmpPanel = (BPMPPanel) tabbedPane.getComponentAt(tab);
          bpmpPanel.loadGraph(inputStream);
        }
      } catch(IOException iE) {
        iE.printStackTrace();
      }
    }
  }
}
